package knowledge;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.beetl.sql.core.ClasspathLoader;
import org.beetl.sql.core.ConnectionSource;
import org.beetl.sql.core.ConnectionSourceHelper;
import org.beetl.sql.core.DefaultNameConversion;
import org.beetl.sql.core.Interceptor;
import org.beetl.sql.core.NameConversion;
import org.beetl.sql.core.SQLLoader;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.UpperCaseUnderlinedNameConversion;
import org.beetl.sql.core.db.PostgresStyle;
import org.beetl.sql.ext.DebugInterceptor;
import org.beetl.sql.ext.gen.GenConfig;
import org.springframework.core.io.ClassPathResource;


public class GenSource {

	public static void main(String[] args) {
		GenSource gen=new GenSource();
		gen.genscript("blog.bg_options");
		
		gen.genbean("blog.bg_options","red.feng.knowledge.model");
	}

	public void genscript(String table){
		SQLManager sqlManager=	connectDb();
		try {
			sqlManager.genSQLTemplateToConsole(table);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public void genbean(String table,String pack){
		
				//PropKit.use("a_little_config.txt", "UTF-8");
				GenConfig config = new GenConfig();
				SQLManager sqlManager=	connectDb();
				try {
						sqlManager.genPojoCode(table, pack);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	}
	
	public SQLManager connectDb(){
		Properties property=new Properties();
		try {
			property.load( new ClassPathResource("jdbc.properties").getInputStream());
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		ConnectionSource source = ConnectionSourceHelper.getSimple(
				(String)property.get("jdbc.driverClassName"),
				(String)property.get("jdbc.url"), 
				(String)property.get("jdbc.username"),
				(String)property.get("jdbc.password"));
		// 采用Postgres习俗
		PostgresStyle mysql = new PostgresStyle();
		// sql语句放在classpagth的/sql 目录下
		SQLLoader loader = new ClasspathLoader("/sql");
		NameConversion nc = new  UpperCaseUnderlinedNameConversion();
		SQLManager sqlManager = new SQLManager(mysql,loader,source,nc,new Interceptor[]{new DebugInterceptor()});
		
		return sqlManager;
	}
}
